package com.zyx.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyx.util.JwtHelper;
import com.zyx.util.Result;
import com.zyx.util.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component//将拦截器注册到spring容器中
public class LoginProtectedInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("token");
        //2.判断是否过期
        if(!jwtHelper.isExpiration(token)){
            return true;
        }
       //3.返回504状态json
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        //4.将result转换为json
        response.getWriter().print(new ObjectMapper().writeValueAsString(result));
        return false;
    }

}
